package org.itboys.weixin.tools;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.utils.encryption.Digests;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 请求校验工具类
 * @author liufeng
 */
public class SignUtil {
	
	/**
	 * 签名算法 将集合M内非空参数值的参数按照参数名ASCII码从小到大排序
	 * 将排序后的map拼接成key1=value1&key2=value2形式
	 * 将字符串MD5加密  并转成大写
	 * @param param
	 * @return
	 */
	public static String sign(Map<String, Object> param){
		System.out.println("排序后的参数值=" + signByASCIISort(param));
		return signToMD5(signByASCIISort(param));
	}
	
	/**
	 * 签名算法 将集合M内非空参数值的参数按照参数名ASCII码从小到大排序
	 * 将排序后的map拼接成key1=value1&key2=value2形式
	 * @param param
	 * @return
	 */
	public static String signByASCIISort(Map<String, Object> param){
		if(param.isEmpty()){
			return null;
		}
		
		StringBuffer sb = new StringBuffer();
		Set<String> keys = param.keySet();
		List<String> keySort = Lists.newArrayListWithExpectedSize(param.size());
		keys.forEach(key ->{
			Object value = param.get(key);
			if(value != null){
				keySort.add(key);
			}
		});
		Collections.sort(keySort);
		
		keySort.forEach(key -> {
			sb.append(key + "=" + param.get(key) + "&");
		});
		return sb.toString().substring(0, sb.toString().length()-1);
	}
	
	/**
	 * 将字符串MD5加密  并转成大写
	 * @param str
	 * @return
	 */
	public static String signToMD5(String str){
		 return Digests.md5(str).toUpperCase();
	}
	
	public static void main(String[] args) {
		String str = "amount=100&check_name=NO_CHECK&desc=恭喜发财，红包送来&mch_appid=760933753c5549d&mchid=1335861101&nonce_str=160428163250264480&openid=oCnQEwbgYDhsv3w04hKxdUntF96I&partner_trade_no=201604201234567891000&spbill_create_ip=115.192.115.16&key=weicangwangluo123456789weicangwa";
		String str2= "amount=100&check_name=NO_CHECK&desc=恭喜发财，红包送来&mch_appid=760933753c5549d&mchid=1335861101&nonce_str=160428163250264480&openid=oCnQEwbgYDhsv3w04hKxdUntF96I&partner_trade_no=201604201234567891000&spbill_create_ip=115.192.115.16&key=weicangwangluo123456789weicangwa";
		System.out.println(StringUtils.equals(str, str2));
	}
	
	/**
	 * 验证签名
	 * 
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static boolean checkSignature(String token,String signature, String timestamp, String nonce) {
		String[] arr = new String[] { token, timestamp, nonce };
		// 将token、timestamp、nonce三个参数进行字典序排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		MessageDigest md = null;
		String tmpStr = null;
		try {
			md = MessageDigest.getInstance("SHA-1");
			// 将三个参数字符串拼接成一个字符串进行sha1加密
			byte[] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		content = null;
		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 * 
	 * @param byteArray
	 * @return
	 */
	private static String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	/**
	 * 将字节转换为十六进制字符串
	 * 
	 * @param mByte
	 * @return
	 */
	private static String byteToHexStr(byte mByte) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
		tempArr[1] = Digit[mByte & 0X0F];

		String s = new String(tempArr);
		return s;
	}
}
